//
//  CookieUtil.m
//  BondWatch
//
//  Created by Jason Yuan on 12/17/15.
//  Copyright © 2015 Jason Yuan. All rights reserved.
//

#import "CookieUtil.h"

@implementation CookieUtil

static CookieUtil *sharedInstance;

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[[self class] alloc] init];
    });
    
    return sharedInstance;
}

- (void)printCookie:(NSString *)url {
    NSHTTPCookieStorage *sharedStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    if ([sharedStorage cookieAcceptPolicy] != NSHTTPCookieAcceptPolicyAlways) {
        [sharedStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    }
    NSArray *cookies = [sharedStorage cookiesForURL:[NSURL URLWithString:url]];
    NSEnumerator *enumerator = [cookies objectEnumerator];
    NSHTTPCookie *cookie;
    while (cookie = [enumerator nextObject]) {
        DDLogWarn(@"%@: %@", [cookie name], [NSString stringWithString:[[cookie value] stringByRemovingPercentEncoding]]);
    }
}

- (void)deleteCookie:(NSString *)url {
    NSHTTPCookieStorage *sharedStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *cookies = [sharedStorage cookiesForURL:[NSURL URLWithString:url]];
    NSEnumerator *enumerator = [cookies objectEnumerator];
    NSHTTPCookie *cookie;
    while (cookie = [enumerator nextObject]) {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }
}

@end
